#include "./hexChar.h"

static int8_t cvtHexChar(int8_t ch, int8_t way) {
  if (way == 0) {
    if (ch >= '0' && ch <= '9') {
      return ch - '0';
    } else if (ch >= 'A' && ch <= 'F') {
      return ch - 'A' + 10;
    } else if (ch >= 'a' && ch <= 'f') {
      return ch - 'a' + 10;
    } else {
      return -1;
    }
  } else {
    if (ch >= 0x00 && ch <= 0x09) {
      return ch + '0';
    } else if (ch >= 0x0A && ch <= 0x0F) {
      return ch - 10 + 'A';
    } else {
      return -1;
    }
  }
}

int cvtStringToHex(char* str, uint8_t* hex) {
  int istr = 0, ihex = 0;
  char hstr, lstr;
  int8_t hhexdata, lhexdata;

  if (str[0] == '0' && (str[1] == 'x' || str[1] == 'X')) {
    istr = 2;
  }
  while (str[istr] != 0x00) {
    hstr = str[istr++];
    if (hstr == 0x20) {
      continue;
    }
    lstr = str[istr++];

    hhexdata = cvtHexChar(hstr, 0);
    lhexdata = cvtHexChar(lstr, 0);
    if (hhexdata < 0 || lhexdata < 0) {
      ERROR("StringToHex");
      return -1;
    }
    hex[ihex++] = (hhexdata << 4) | lhexdata;
  }
  return ihex;
}
int cvtHexToString(uint8_t* hex, int len, char* str) {
  int istr = 0, ihex = 0;

  for (ihex = 0; ihex < len; ihex++) {
    str[istr++] = cvtHexChar(hex[ihex] >> 4, 1);
    str[istr++] = cvtHexChar(hex[ihex] & 0x0F, 1);
  }
  str[istr] = 0x00;
  return istr;
}
